package com.dynamic.mybatis.core.generator.helper;

import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.metadata.MappedStatementField;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;

import java.util.Optional;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 16:28
 */
public class OptimisticLockInjectorHelper extends InjectorHelper {

    /**
     * 获取乐观锁相关
     *
     * @param table 表信息
     * @return String
     */
    public static String optlockVersion(MappedStatementTable table) {
        Optional<MappedStatementMetaField> optimisticLockField;
        if ((optimisticLockField =getOptimisticLock(table)).isPresent()) {
            return getVersionOli(optimisticLockField.get(),ENTITY, ENTITY_DOT);
        }
        return EMPTY;
    }

    public static String getVersionOli(MappedStatementField field,final String alias, final String prefix) {
        final String oli = " AND " + field.getColumn() + EQUALS + SqlScriptUtils.safeParam(MP_OPTLOCK_VERSION_ORIGINAL);
        final String ognlStr = convertIfProperty(prefix, field.getField());
        if (field.getJavaTypeClass().equals(String.class)) {
            return SqlScriptUtils.convertIf(oli, String.format("%s != null and %s != null and %s != ''", alias, ognlStr, ognlStr), false);
        } else {
            return SqlScriptUtils.convertIf(oli, String.format("%s != null and %s != null", alias, ognlStr), false);
        }
    }
}